package com.wyj.http;

import com.wyj.util.HttpProtocolUtil;
import com.wyj.util.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * TODO: 响应信息
 *
 * @author wuyijie
 * @date 2021/12/12 10:22
 */
public class Response {
    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * TODO: 输出流输出内容
     *
     * @param content
     * @author wuyijie
     * @date 2021/12/16 3:48 下午
     */
    public void write(String content) throws Exception {
        try {
            outputStream.write((content).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param path url，随后要根据url来获取到静态资源的绝对路径，进⼀步根据绝对路径
     *             读取该静态资源⽂件，最终通过
     *             输出流输出
     *             /-----> classes
     */
    public void outputHtml(String path) throws Exception {
// 获取静态资源⽂件的绝对路径
        String absoluteResourcePath =
                StaticResourceUtil.getAbsolutePath(path);
// 输⼊静态资源⽂件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
// 读取静态资源⽂件，输出静态资源
            StaticResourceUtil.outputStaticResource(new
                    FileInputStream(file), outputStream);
        } else {
// 输出404
            write(HttpProtocolUtil.get404Headers());
        }
    }
}
